﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using log4net;

namespace CentrisScraper.Lib
{
    public class ScraperServiceRunner
    {
        private bool stopped = false;
        private readonly ILog log = LogManager.GetLogger("ScraperServiceRunner");

        public void Run()
        {
            while (!stopped)
            {
                try
                {

                    DateTime[] dates = { DateTime.Now.AddDays(-9), DateTime.Now.AddDays(-8), DateTime.Now.AddDays(-7), DateTime.Now.AddDays(-6), DateTime.Now.AddDays(-5), DateTime.Now.AddDays(-4), DateTime.Now.AddDays(-3), DateTime.Now.AddDays(-2), DateTime.Now.AddDays(-1), DateTime.Now };
                    foreach (var date in dates)
                    {
                        // ventes
                        var listings = ListingScraper.GetListingsForVentes(date);
                        Notifier.SendNotificationFor(listings, "Ventes");

                        // locations
                        listings = ListingScraper.GetListingsForLocations(date);
                        Notifier.SendNotificationFor(listings, "Locations");
                    }
                }
                catch (Exception e)
                {
                    log.Error("ScraperServiceRunner Run error", e);
                }
                Thread.Sleep(60*60*1000); // 1 heure
            }
        }

        public void Stop()
        {
            stopped = true;
        }

        public static ScraperServiceRunner New()
        {
            var threadProcess = new ScraperServiceRunner();
            var thread = new Thread(threadProcess.Run);
            thread.Start();
            return threadProcess;
        }
    }
}
